<?php

namespace app\api\controller;

use app\lib\exception\ParameterException;
use app\admin\model\Image;
use app\admin\model\Member AS MemberMdl;
use app\admin\model\Povertyproject;
use app\admin\model\Organization;
use app\admin\model\Villages;
use app\admin\model\Povertypolicy;
use app\admin\model\Povertymember;

use think\Exception;

/**
 * 村民接口
 */
class Member extends BaseController
{

    /**
     * 获取村民列表
     *
     * @return \think\response\Json
     */
    public function getMemberList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId,
            'villageId' => $param->villageId,
            'checkVillager' => 1,
            'isDelete' => 2
        ];
        $fields = 'id, name, avatar, isPoverty, organizationId, job';
        $result = MemberMdl::where($where)->order('sorting ASC,createDate DESC')->limit($start, $length)->field($fields)->select();
        $total = MemberMdl::where($where)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到村民');
        }

        foreach ($result as $item) {
            if($item['organizationId']){
                $organization = Organization::where(['id' => $item['organizationId']])->value('name');
                $item['organization'] = $organization;
                $item['job'] = $item['job'];
            }
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 获取村民详情
     *
     * @return \think\response\Json
     */
    public function getMemberDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        /*if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }*/
        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能这空');
        }

        $memberId = $param->memberId;
        $where = [
            'townId' => $param->townId,
            //'villageId' => $param->villageId,
            'id' => $memberId
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = $param->villageId;
        }

        $model = new MemberMdl();
        $fields = 'name, avatar, isPoverty, gender, birthday, mobile, ethnicId, address, checkParty, checkInstitution, checkVillager, checkPoverty';
        $item = $model->where($where)->field($fields)->find();

        if (empty($item)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关村民');
        }

        // 家庭环境
        $familyImgs = Image::where(['relatedId' => $memberId, 'relatedTable' => 'member', 'tag' => 'imglist'])->field('imgUrl')->select();
        $item['familyImgs'] = $familyImgs;
        // 享受政策
        //$policyImgs = Image::where(['relatedId' => $memberId, 'relatedTable' => 'member', 'tag' => 'policyimglist'])->field('imgUrl')->select();
        //$item['policyImgs'] = $policyImgs;
        $povertypolicyList = Povertypolicy::alias('a')->where(['a.memberId' => $memberId])->join('povertypolicyledger b', 'a.policyledgerId = b.id')->field('a.policy, b.year')->select();
        $povertypolicy = [];
        if($povertypolicyList){
            foreach ($povertypolicyList as $povertypolicys) {
                $policyList = json_decode($povertypolicys['policy'], true);
                $totalAmount = 0;
                foreach ($policyList as $policy) {
                    if(count($policy['policySpec']) > 1){
                        // 多列
                        foreach($policy['policySpec'] as $policySpec){
                            if($policySpec['explain'] == 1){
                                $totalAmount += $policySpec['explainValue'];
                            }
                        }
                    }else{
                        // 一列
                        $policySpec = $policy['policySpec'][0];
                        if($policySpec['explain'] == 1){
                            $totalAmount += $policySpec['explainValue'];
                        }
                    }
                }
                $povertypolicy[] = [
                    'year' => $povertypolicys['year'],
                    'countPolicy' => count($policyList),
                    'totalAmount' => $totalAmount
                ];
            }
        }
        $item['povertypolicy'] = $povertypolicy;

        // 贫困户信息
        $povertyInfo = Povertymember::where(['memberId' => $memberId])->field('povertydegree, povertyreason, outpoverty, outPovertyYear, aidingId')->find();
        $item['povertyInfo'] = $povertyInfo;

        // 扶贫项目
        $povertyprojects = Povertyproject::where(['memberId' => $memberId, 'isDelete' => 2])->field('id, title, imgUrl')->select();
        $item['povertyprojects'] = $povertyprojects;

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 组织成员详情
     */
    public function getPartyDetail()
    {
        $param = self::getHttpParam();
        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'memberId 不能为空');
        }
        $row = MemberMdl::where(['id' => $param->memberId])->field('name,job,avatar,partyTime,ethnicId,education,mobile')->find();
        // 小程序背景图
        $row['bgImage'] = 'https://' . $_SERVER['HTTP_HOST'] . '/public/static/wechat/image/memberinfo_bg.png';
        $row['avatar'] = $row['avatar'] . '?imageView2/1/w/110/h/110';

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $row);
    }

    //我的->我是村民详情
    /*public function getMyDetails()
    {
        $param = self::getHttpParam();
        $userId = $param->userId;
        try {
            if (!$userId) {
                throw new ParameterException([
                    'msg' => '缺少参数'
                ]);
            }
            $user = \app\admin\model\User::get($userId);
            $Member = \app\admin\model\Member::where(['userId' => $userId, 'isDelete' => 2])->find();
            //$Member = \app\admin\model\Member::where(['id' => $user->memberId, 'isDelete' => 2])->find();
            if ($Member) {
                $Member->partyTime = date('Y-m-d H:i:s', $Member->partyTime);
                if ($Member->organizationId) {
                    $Organization = \app\admin\model\Organization::get($Member->organizationId);
                    if ($Organization) {
                        $Member['Organizationname'] = $Organization->name;
                    }
                }
                if ($Member->villageId) {
                    $villagename = getVillageName($Member->villageId);
                    if ($villagename) {
                        $Member['villagename'] = $villagename;
                    }
                }
                $user['member'] = $Member;
            }
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $user);
        } catch (Exception $ex) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, isset($ex->msg) ? $ex->msg : $ex->getMessage());
        }
    }*/

    /**
     * 获取贫困户列表
     *
     * @return \think\response\Json
     */
    public function getPovertyMembers()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        /*if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }*/
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId,
            //'villageId' => $param->villageId,
            'checkPoverty' => 1,
            'isPoverty' => 1,
            'isDelete' => 2
        ];
        if (isset($param->villageId) && $param->villageId) {
            $where['villageId'] = ['in', ['0', $param->villageId]];
        }
        // 筛选
        if (isset($param->name) && $param->name) {
            $where['name'] = ['like', '%' . $param->name . '%'];
        }
        $fields = 'id, name, avatar, isPoverty, organizationId, job, villageId, userId';
        $result = MemberMdl::where($where)->order('sorting ASC,createDate DESC')->limit($start, $length)->field($fields)->select();
        $total = MemberMdl::where($where)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到贫困户');
        }

        foreach ($result as $item) {
            if($item['organizationId']){
                $organization = Organization::where(['id' => $item['organizationId']])->value('name');
                $item['organization'] = $organization;
                $item['job'] = $item['job'];
            }
            $village = Villages::where(['id' => $item['villageId']])->value('name');
            $item['village'] = $village;
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 领导干部列表
     */
    public function getCadreList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId,
            'villageId' => $param->villageId,
            //'institutionJob' => ['neq', ''],
            //'villageJob' => ['neq', ''],
            'isDelete' => 2,
        ];
        //$whereStr = "(`institutionJob` <> '') OR (`villageJob` <> '')";
        //$whereStr = "(`job` <> '') OR (`villageJob` <> '')";
        $whereStr = "(checkParty = 1 OR checkInstitution = 1 OR checkVillager = 1 OR checkPoverty = 1) AND (`job` <> '' OR `villageJob` <> '')";

        $fields = 'id, name, avatar, gender, job, institutionJob, villageJob, userId';
        $result = MemberMdl::where($where)->where($whereStr)->order('sorting ASC,createDate DESC')->field($fields)->limit($start,$length)->select();
        $total = MemberMdl::where($where)->where($whereStr)->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到领导干部');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 党员列表
     */
    public function getPartyList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        /*if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }*/
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.townId' => $param->townId,
            'a.isDelete' => 2,
            'a.isParty' => 1,
            'a.checkParty' => 1,
        ];
        if(isset($param->name) && $param->name) {
            $where['a.name'] = ['like', '%' . $param->name . '%'];
        }
        if(isset($param->memberId) && $param->memberId) {
            $where['a.id'] = ['neq', $param->memberId];
        }

        $fields = 'a.id, a.name, a.avatar, a.gender, a.job, a.identityNumber';
        $result = MemberMdl::alias('a')->where($where)->join('organization b','a.organizationId=b.id')->field($fields)->limit($start,$length)->select();
        $total = MemberMdl::alias('a')->where($where)->join('organization b','a.organizationId=b.id')->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到党员');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 户主列表
     */
    public function getHouseholderList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        /*if (empty($param->villageId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'villageId 不能为空');
        }*/
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'a.townId' => $param->townId,
            'a.isDelete' => 2,
            'a.checkVillager' => 1,
            'b.isHouseholder' => 1
        ];

        $fields = 'a.id, a.name, a.avatar, a.gender, a.job, a.identityNumber';
        $result = MemberMdl::alias('a')->where($where)->join('memberextrainfo b','a.id=b.memberId')->field($fields)->limit($start,$length)->select();
        $total = MemberMdl::alias('a')->where($where)->join('memberextrainfo b','a.id=b.memberId')->count();

        if (empty($result)) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到户主');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

}